package dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class DaoJPA implements Dao {
	private static DaoJPA dao;
	
	public static DaoJPA getDAO() {
		if (dao == null)
			dao = new DaoJPA();
		return dao;
	}
	
	private EntityManagerFactory emf = 
		Persistence.createEntityManagerFactory("Vestas");
	private EntityManager em = emf.createEntityManager();
	private EntityTransaction tx = em.getTransaction();
	
	private DaoJPA () {
		// singleton
	}
	
	@Override
	public synchronized <T> T find(Class<T> clazz, Object id) {
		return em.find(clazz, id);
	}

	@Override
	public synchronized <T> List<T> get(Class<T> clazz) {
        return em.createQuery("SELECT e FROM " + 
        	clazz.getSimpleName() + " e", clazz).getResultList();
	}

	@Override
	public synchronized <T> void persist(T object) {
		tx.begin();
		em.persist(object);
		tx.commit();
	}

	@Override
	public synchronized void update() { // updates all managed entities
		tx.begin();
		tx.commit();
	}

	@Override
	public synchronized <T> void remove(T managed) {
		tx.begin();
		em.remove(managed);
		tx.commit();
	}
	
	@Override
	public synchronized void clear() {
		em.clear();
	}
}